from django.test import TestCase, TransactionTestCase
from events.service.purchase_simulator_service import PurchaseSim
from events.models import StoreSalesOrder, StoreSalesOrderDetail
from events.service.purchase_threading import PurchaseThread


import pandas as pd
import time

class PurchaseSimulatorTest(TestCase):
    def setUp(self):
        pd.set_option('display.max_columns', None)
        pd.set_option('display.max_rows', None)

    def test_get_order(self):
        latest_order = StoreSalesOrder.objects.latest('created_at')
        print(f"订单号: {latest_order.order_id}")

    def test_purchase_simulation(self):
        """测试购物模拟器及数据库插入"""
        for i in range(10):
            print(f"\n=== 第 {i+1} 次模拟购物 ===")
            simulator = PurchaseSim()
            purchased_product = simulator.purchase()
            
            if not simulator.consumer.blanket:
                print("该顾客没有购买任何商品")
                continue
                
            # 插入购买数据到数据库
            simulator.insert_purchase_data(purchased_product)
            
            # 验证数据是否正确插入到数据库
            latest_order = StoreSalesOrder.objects.latest('created_at')
            order_details = StoreSalesOrderDetail.objects.filter(order_id=latest_order.order_id)
            
            print("\n成功创建订单:")
            print(f"订单号: {latest_order.order_id}")
            print(f"订单总金额: {latest_order.retail_price}")
            print(f"商品数量: {order_details.count()}")
            
            print("\n订单明细:")
            from product.models import ProductsInventory
            for detail in order_details:
                # 获取商品当前库存
                inventory = ProductsInventory.objects.get(product_code=detail.product_code)
                print(f"商品编码: {detail.product_code}")
                print(f"购买数量: {detail.quantity}")
                print(f"当前库存: {inventory.instock_quantity}")
                print("-" * 30)
            
            # 验证订单总金额是否正确
            total_price = sum(product['default_retail_price'] for product in simulator.consumer.blanket)
            self.assertEqual(float(latest_order.retail_price), total_price)

    def test_multiple_customers_simulation(self):
        """测试多个顾客同时购物的场景"""
        # 创建购物模拟器实例，设置最大线程数为4
        simulator = PurchaseThread(max_threads=4)
        
        # 启动模拟器
        simulator.start()
        
        # 等待一段时间让模拟器运行（例如30秒）
        time.sleep(30)
        
        # 停止模拟器
        simulator.stop()
        
        # 验证是否有订单生成
        orders = StoreSalesOrder.objects.all()
        self.assertGreater(orders.count(), 0, "应该至少生成一个订单")
        
        print(f"\n=== 多顾客购物模拟结果 ===")
        print(f"总共生成订单数: {orders.count()}")
        
        # 验证每个订单的详细信息
        for order in orders:
            order_details = StoreSalesOrderDetail.objects.filter(order_id=order.order_id)
            print(f"\n订单号: {order.order_id}")
            print(f"订单总金额: {order.retail_price}")
            print(f"订单商品数量: {order_details.count()}")
            print(f"完成时间: {order.finished_at}")
            
            # 验证订单明细
            self.assertGreater(order_details.count(), 0, "每个订单应该至少包含一件商品")
            
            print("\n订单明细:")
            for detail in order_details:
                print(f"商品编码: {detail.product_code}")
                print(f"购买数量: {detail.quantity}")
                print("-" * 30)
